package com.yuguoxy.mytomcat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class YGTomcat {
    private int port = 8080;  //端口
    private Map<String, String> urlMap = new HashMap<>(); //url <->Servlet

    private void initUrlServlet() {
        for (ServletMapping servletMapping : ServletMappingConfig.servletMappingLists) {
            urlMap.put(servletMapping.getUrl(), servletMapping.getServletClaszz());
        }
    }

    private void dispath(YGHttpRequest request, YGHttpResponse response) {
        if(request.getUrl().equalsIgnoreCase("/favicon.ico")){
            return;
        }
        String clazz = urlMap.get(request.getUrl()); //request.getUrl()->请求包解析得到的url,
        System.out.println(clazz);
        try {
            Class<YGHttpServlet> servletClass = (Class<YGHttpServlet>) Class.forName(clazz);
            YGHttpServlet servlet = servletClass.newInstance();
            servlet.service(request, response);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

    /**
     * 启动服务
     */
    public void start() {
        initUrlServlet();
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("my tomcat is start...");
            while (true) {
                Socket socket = serverSocket.accept();
                InputStream inputStream = socket.getInputStream();
                OutputStream outputStream = socket.getOutputStream();

                YGHttpRequest request = new YGHttpRequest(inputStream);
                YGHttpResponse response = new YGHttpResponse(outputStream);

                dispath(request, response);

                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String args[]) {
        new YGTomcat().start();
    }
}
